import React, { useState } from 'react';
import { Input, Button, Upload, MessagePlugin } from 'tdesign-react';
import { UploadIcon } from 'tdesign-icons-react';
import { uploadImage } from '../../services/uploadService';
import './CoverImageUpload.css';

interface CoverImageUploadProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
}

export default function CoverImageUpload({ value, onChange, placeholder }: CoverImageUploadProps) {
  const [uploading, setUploading] = useState(false);

  const handleFileChange = async (file: File) => {
    setUploading(true);
    try {
      const response = await uploadImage(file);
      if (response.code === 200) {
        onChange?.(response.data.url);
        MessagePlugin.success('图片上传成功');
      } else {
        MessagePlugin.error(response.message || '图片上传失败');
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      MessagePlugin.error('图片上传失败');
    } finally {
      setUploading(false);
    }
    return false; // 阻止默认上传行为
  };

  const handleUrlChange = (url: string) => {
    onChange?.(url);
  };

  const handleRemove = () => {
    onChange?.('');
  };

  return (
    <div className="cover-image-upload">
      {value ? (
        <div className="cover-preview">
          <img
            src={value}
            alt="封面预览"
            loading="lazy"
            onError={() => {
              MessagePlugin.error('图片加载失败，请检查URL是否正确');
            }}
          />
          <div className="cover-actions">
            <Button size="small" theme="danger" onClick={handleRemove}>
              移除封面
            </Button>
          </div>
        </div>
      ) : (
        <div className="cover-upload-area">
          <Input
            value={value || ''}
            onChange={(val) => handleUrlChange(val)}
            placeholder={placeholder || '请输入封面图URL或上传图片'}
            clearable
          />
          <Upload
            autoUpload={false}
            onChange={(files: any) => {
              if (files && files.length > 0 && files[0].raw) {
                const file = files[0].raw as File;
                handleFileChange(file);
              }
            }}
            accept="image/*"
            disabled={uploading}
            showUploadProgress={false}
          >
            <Button
              theme="primary"
              variant="outline"
              disabled={uploading}
              icon={<UploadIcon />}
            >
              {uploading ? '上传中...' : '上传图片'}
            </Button>
          </Upload>
        </div>
      )}
    </div>
  );
}
